package com.gk.javaservice.util.javaRequest;


import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Base64;


public class PostMethodUtils {
    private Logger log = Logger.getLogger(this.getClass());

    //孙逸仙南院

    /**
     * 发送HttpClient请求
     *
     * @param requestUrl
     * @param params
     * @return
     */
    public static String sendPost(String requestUrl, String params) {
        InputStream inputStream = null;
        try {
            HttpClient httpClient = new HttpClient();
            PostMethod postMethod = new PostMethod(requestUrl);
            // 设置请求头  Content-Type
            postMethod.setRequestHeader("Content-Type", "application/json");
            //Base64加密方式认证方式下的basic auth HAIN460000：用户名    topicis123：密码
            postMethod.setRequestHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString(("HAIN460000" + ":" + "topicis123").getBytes()));
            RequestEntity requestEntity = new StringRequestEntity(params, "application/json", "UTF-8");
            postMethod.setRequestEntity(requestEntity);
            httpClient.executeMethod(postMethod);// 执行请求
            inputStream = postMethod.getResponseBodyAsStream();// 获取返回的流
            BufferedReader br = null;
            StringBuffer buffer = new StringBuffer();
            // 将返回的输入流转换成字符串
            br = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
            }
//            log.info("接口返回内容为:" + buffer);
            // System.out.println("接口返回内容为:" + buffer);
            return buffer.toString();
        } catch (Exception e) {
//            log.info("请求异常" + e.getMessage());
            // System.out.println("请求异常" + e.getMessage());
            throw new RuntimeException(e.getMessage());
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        String parameter = "{ \"dto\":{\"purchaserPhone\":\"13798479813\" }}";
        String requestUrl= "";
        PostMethodUtils.sendPost(requestUrl,parameter);
    }

}
